# çæé·è¾¾åæ³¢ä¿¡å·
import torch
from apps.exp.exp_config import ExpConfig as EG

class EchoSignal(object):
    def __init__(self):
        self.name = 'apps.exp.echo_signal.EchoSignal'

    # ==============================
    # ç®æ å²æ¿€ååºç©éµæé€ 
    # ==============================
    @staticmethod
    def build_H_matrix(params, N, T, f0):
        """æå»ºåä¸ªç®æ çå²æ¿€ååºç©éµ"""
        r, v, alpha = params["r"], params["v"], params["alpha"]
        
        # è®¡ç®æ¶å»¶åæ ·æ¬åç§»
        tau = 2 * r / EG.c               # ååä¼ æ­æ¶å»¶
        d_samples = int(round(tau / T))  # æ¶å»¶å¯¹åºçæ ·æ¬æ°
        
        # è®¡ç®å¤æ®åé¢ç
        fd = 2 * v * f0 / EG.c  # å¤æ®åé¢ç§»
        
        # ç´¢å¼ç©éµ
        i_idx, j_idx = torch.meshgrid(torch.arange(N), torch.arange(N), indexing='ij')
        
        # å²æ¿€ååºç©éµåå§å
        H = torch.zeros((N, N), dtype=torch.complex64)
        
        if 0 <= d_samples < N:
            # æ¶å»¶æ©ç  (i-j = d_samples)
            delay_mask = (i_idx - j_idx) == d_samples
            
            # å¤æ®åç¸ä½è¡¥å¿ç©éµ
            t_matrix = i_idx.float() * T  # æ¥æ¶æ¶é´è½´
            phase_shift = torch.exp(1j * 2 * torch.pi * fd * t_matrix)
            
            # ç»åå²æ¿€ååº
            H[delay_mask] = alpha * phase_shift[delay_mask]
        
        return H
    
    @staticmethod
    def generate_signal(s:torch.Tensor) -> torch.Tensor:
        # æå»ºæ€»å²æ¿€ååºç©éµ
        H_total = torch.zeros((EG.N, EG.N), dtype=torch.complex64)
        for target in EG.targets:
            H_total += EchoSignal.build_H_matrix(target, EG.N, EG.Ts, EG.f0)
        # ==============================
        # åæ³¢ä¿¡å·çæ
        # ==============================
        y = H_total @ s  # ç©éµä¹æ³å®ç°çº¿æ€§å·ç§¯
        return y